/*
作者：江怀玉
日期：2014-05-09
功能：字典控件
解决：
1、取数据问题
2、条件
3、数据显示
4、选值
-------------------------------------
依赖:
jquery,
/scripts/jquery.data.js :fnGetData
---------------------------------------------------------*/
(function ($) {
    $.fn.Dictionary = function (options) {
        //debugger
        var _opt = !options ? { "entity": "V_User"} : options;
        var v = $(this).attr("valuemember");   //值字段
        var d = $(this).attr("displaymember"); //显示在控件中字段
        var c = $(this).attr("class");         //分类值
        var f = $(this).attr("filter");        //过滤字段
        //var t = $(this).attr("top");           //显示几行
        var lw = $(this).attr("listwidth");    //弹出的列表宽度
        var l = $(this).attr("listMember");    //显示的列表字段
        var _l = l == undefined || l == "" ? [{ F: "caption", W: "250px"}] : eval(l); //显示的列表字段
        var arrayf = new Array();              //定义要过滤的字段组
        arrayf = f.split(',');

        var defaults = {
            id: $(this).attr("id"),
            entity: $(this).attr("entity"), //对应实体 
            sort: $(this).attr("sort"),    //排序
            filter: f == undefined || f == "" ? "caption" : f,        //过滤字段
            valuemember: v == undefined || v == "" ? "id" : v,        //值字段
            displaymember: d == undefined || d == "" ? "caption" : d, //显示字段
            top: t == undefined || t == "" ? "25" : t,                //
            list: _l,                                                 //显示列表
            listwidth: lw,                                              //显示弹出的列表宽度
            event: $(this).attr("event")                               //事件方法
        };


        $(this).wrap("<div id=\"Dept_" + defaults.CtrolID + "\" class=\"deptctrl\" style=\"width:" + (this.width() + 20) + "px\"></div>");
        $(this).width(this.width() - 16);
        $(this).after('<input type="button" class="button" id="btn_' + defaults.CtrolID + '"/>');
        //        $("#btn_" + defaults.CtrolID).click(function (event) {
        //            fn($("#" + defaults.CtrolID).val(), event);
        //        })
        //GetData($(this).attr("entity"), $(this).attr("condition"), $(this).attr("sort"));

        function GetData(entity, condition, sort) {
            return fnGetData(entity, condition, "", "YES");
        }

        //搜索条件
        function getCondition(key, _fields) {
            var _condition = "";

            for (i = 0; i < _fields.length; i++) {
                if (i == 0) {
                    _condition = _condition + " (" + _fields[i] + " like '%" + key + "%')  ";
                }
                else {
                    _condition = _condition + " or (" + _fields[i] + " like '%" + key + "%')  "
                }
            }

            return _condition;
        }

        var o_value = "";
        var timer = 0; //记时器

        SetDataTable(); var o_value = "";
        var timer = 0; //记时器
        $(this).bind("keyup", function (e) {
            if (e.which != 13 && e.which != 40 && e.which != 38) {
                //debugger
                if (o_value == $(this).val()) {
                    return;
                }
                o_value = $(this).val();

                //-------用来确保只执行一次有效的数据拉取
                clearTimeout(timer);
                timer = setTimeout(SetDataTable, 1000);
            }
        }).focus(function () {
            $(this).select();
        });

        var _data = null;
        function SetDataTable() {
            var key = o_value;
            var condition = getCondition(key, arrayf);
            _data = GetData(defaults.entity, condition);
            if (_data == undefined) {
                LoadData(null);
            }
            if (_data == null) {
                LoadData(null);
            }
            LoadData(_data.rows);
        }


        // 加载数据
        function LoadData(rows) {
            var html = "";
            var _slist = defaults.list;
            if (rows == null || rows == undefined) {
                cols =
                html = "<tr><td colspan=\"" + _l.length + "\"></td><tr>";
            } else {
                for (var i = 0; i < rows.length; i++) {
                    var list = rows[i];
                    html += "<tr index='" + i + "'>";
                    for (var _index = 0; _index < _slist.length; _index++) {
                        html += '<td style="width: ' + _slist[_index].W + ';">' + rows[i][_slist[_index].F] + '</td>';
                    }
                    html += "</tr>";
                }
            }

            //点击事件回调
            autocomplete(defaults.id, "200px", "220px", html, function (r) {
                $("#" + defaults.id).attr("SValue", r[defaults.valuemember]);
                $("#" + defaults.id).val(r[defaults.displaymember]);
            });
        }
        //方向键上,方向键下,回车键
        function autocompletekeydown(Objkey, callBack) {
            $("#" + Objkey).keydown(function (e) {
                switch (e.keyCode) {
                    case 38: // 方向键上
                        if (IndetableRow_autocomplete > 0) {
                            IndetableRow_autocomplete--
                            $("#div_gridshow").find('tbody tr').removeClass('selected');
                            $("#div_gridshow").find('tbody tr').each(function (r) {
                                if (r == IndetableRow_autocomplete) {
                                    scrollTopheight -= $(this).height();
                                    $("#div_gridshow").scrollTop(scrollTopheight);
                                    $(this).addClass('selected');
                                }
                            });
                        }
                        break;
                    case 40: // 方向键下
                        var tindex = $("#div_gridshow").find('tbody tr').length - 1;
                        if (IndetableRow_autocomplete < tindex) {
                            IndetableRow_autocomplete++;
                            $("#div_gridshow").find('tbody tr').removeClass('selected');
                            $("#div_gridshow").find('tbody tr').each(function (r) {
                                if (r == IndetableRow_autocomplete) {
                                    scrollTopheight += $(this).height();
                                    $("#div_gridshow").scrollTop(scrollTopheight);
                                    $(this).addClass('selected');
                                }
                            });
                        }
                        break;
                    case 13:  //回车键

                        if ($('#' + Objkey).attr('readonly') == 'readonly') {
                            return false;
                        }
                        if ($('#' + Objkey).attr('disabled') == 'disabled') {
                            return false;
                        }

                        var _index = IndetableRow_autocomplete;
                        var _e = _data.rows[_index];
                        callBack(_e);
                        $("#div_gridshow").hide();

                        break;
                    default:
                        break;
                }
            })
        }

        //上，下键盘回调
        autocompletekeydown(defaults.id, function (obj) {
            //var array = new Array();
            //array = r.split('≌');
            //设置值
            $("#" + defaults.id).val(obj[defaults.displaymember]);
            $("#" + defaults.id).attr("SValue", obj[defaults.valuemember]);
        });




        //自动补全表格
        var IndetableRow_autocomplete = 0;
        var scrollTopheight = 0;
        function autocomplete(Objkey, width, height, data, callBack) {
            if ($('#' + Objkey).attr('readonly') == 'readonly') {
                return false;
            }
            if ($('#' + Objkey).attr('disabled') == 'disabled') {
                return false;
            }
            IndetableRow_autocomplete = 0;
            scrollTopheight = 0;
            var X = $("#" + Objkey).offset().top;
            var Y = $("#" + Objkey).offset().left;
            $("#div_gridshow").html("");
            if ($("#div_gridshow").attr("id") == undefined) {
                $('body').append('<div id="div_gridshow" style="overflow: auto;z-index: 1000;border: 1px solid #A8A8A8;border-top: 0px solid #A8A8A8;width:' + width + ';height:' + height + ';position: absolute; background-color: #fff; display: none;"></div>');
            } else {
                $("#div_gridshow").height(height);
                $("#div_gridshow").width(width);
            }
            var sbhtml = '<table class="tableobj">';
            if (data != "") {
                sbhtml += '<tbody>' + data + '</tbody>';
            } else {
                sbhtml += '<tbody><tr><td style="color:red;text-align:center;width:' + width + ';">没有找到您要的相关数据！</td></tr></tbody>';
            }
            sbhtml += '</table>';
            $("#div_gridshow").html(sbhtml);
            $("#div_gridshow").css("left", Y).css("top", X + 25).show();
            if (data != "") {
                $("#div_gridshow").find('tbody tr').each(function (r) {
                    if (r == 0) {
                        $(this).addClass('selected');
                    }
                });
            }
            $("#div_gridshow").find('tbody tr').click(function () {
                if ($('#' + Objkey).attr('readonly') == 'readonly') {
                    return false;
                }
                if ($('#' + Objkey).attr('disabled') == 'disabled') {
                    return false;
                }
                var _index = parseInt($(this).attr("index"));
                var _e = _data.rows[_index];
                callBack(_e);
                $("#div_gridshow").hide();
            });
            $("#div_gridshow").find('tbody tr').hover(function () {
                $(this).addClass("selected");
            }, function () {
                $(this).removeClass("selected");
            });

            //任意键关闭
            document.onclick = function (e) {
                var e = e ? e : window.event;
                var tar = e.srcElement || e.target;
                if (tar.id != 'div_gridshow') {
                    if ($(tar).attr("id") == 'div_gridshow' || $(tar).attr("id") == Objkey) {
                        $("#div_gridshow").show();
                    } else {
                        $("#div_gridshow").hide();
                    }
                }
            }
        }
    }

})(jQuery);



//初始化控件
$(document).ready(function () {
        var controls = $(this).find('input');
        controls.each(function () {
           if ($(this).attr("ctrlType") == "Commbox") {
              $(this).Commbox();
   }
});
});
/*
-------------------------------------
样例:
<input type="text" SValue="" SText="" id="Dept" value="" ctrlType="AutoComplete" SelectMode="s" entity="V_Dept" filter="DeptPath,name" valuemember="DeptPath" displaymember="name" listMember="[{F:'name',W:'150px'},{F:'DeptPath',W:'120px'}]"/>
<input type="text" SValue="" SText="" id="UName" value="" ctrlType="AutoComplete" SelectMode="s" entity="DatUser" filter="LoginName,UName" valuemember="LoginName" displaymember="UName" listMember="[{F:'LoginName',W:'150px'},{F:'UName',W:'120px'}]"/>
-------------------------------------
另：
//(function ($) {
//    $.fn.delayKeyup = function (callback, ms) {
//        var timer = 0;
//        $(this).keyup(function () {
//            clearTimeout(timer);
//            timer = setTimeout(callback, ms);
//        });
//        return $(this);
//    };
//})(jQuery)；f
*/